/*
 * Created on Feb 9, 2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.broadvision.manage.common.tools.action.common;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.broadvision.data.client.Category;
import com.broadvision.data.client.Content;
import com.broadvision.data.client.DataManager;
import com.broadvision.data.client.Qualifier;
import com.broadvision.data.common.CallSettings;
import com.broadvision.data.common.ContentUID;
import com.broadvision.data.common.DataConstants;
import com.broadvision.data.common.DataValue;
import com.broadvision.data.exceptions.DataException;
import com.broadvision.data.sql.SQLCompoundCondition;
import com.broadvision.data.sql.SQLCondition;
import com.broadvision.data.sql.SQLConditionFactory;
import com.broadvision.data.sql.SQLOperator;
import com.broadvision.ssp.util.TableConstants;
import com.broadvision.web.util.ViewDynaBean;

/**
 * @author kwlee
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class CategorySearchPickerPopupAction extends SearchCntPickerPopupAction {
  
  public static String CATEGORY_BROWSE_PATH = "mt.categoryOnly.browse.path";
  public static String CATEGORY_SEARCH_PATH = "mt.categoryOnly.search.path";
  
  public static String CONTENT_TYPE = "CONTENT_TYPE";

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#getTabPageMap()
   */
  protected String[][] getTabPageMap(HttpServletRequest request) {
    String[][] tabPageMap = {{getMessage(request, BROWSE), getMessage(request, CATEGORY_BROWSE_PATH), "browseTab"},
                             {getMessage(request, SEARCH), getMessage(request, CATEGORY_SEARCH_PATH), "searchTab"}};
    return tabPageMap;
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.tools.action.BaseAction#processExecute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  protected ActionForward processExecute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
      
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    if (pickerPopupForm == null || mapping == null) {
      request.setAttribute(Globals.ERROR_KEY, "error.application");
      return mapping.findForward("failure");
    }// if

/*** set "categoryOnly" to true */
    PropertyUtils.setSimpleProperty(pickerPopupForm, 
                                    "categoryOnly", 
                                    new Boolean(true));

    return super.processExecute(mapping, form, request, response);
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#getList(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public List getList(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
      
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    List resultList = new ArrayList();    
    String searchKey = (String)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchKey");
    boolean allCategories = ((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "allCategories")).booleanValue();
    int currentCategoryOid = ((Long)PropertyUtils.getSimpleProperty(pickerPopupForm, "currentCategoryOid")).intValue();
    boolean searchBtnNeverClicked = ((Boolean)PropertyUtils.getSimpleProperty(pickerPopupForm, "searchBtnNeverClicked")).booleanValue();
  
    String columnName = getColumnName(mapping, form, request, response);

    if (searchBtnNeverClicked) {
      // TODO: display default search result
      long[] defaultIds = getDefaultSearchResultList(mapping, form, request, response);
      if (defaultIds.length != 0) {
        try {
          DataManager dm = new DataManager();
          CallSettings callsettings = dm.getCallSettings();
          callsettings.setFilteringFlag(false);
          ArrayList attributesList = new ArrayList(3);
          attributesList.add(OID);
          attributesList.add(columnName);
          attributesList.add(CONTENT_TYPE);
          resultList = dm.getPartialContents(DataConstants.DEFAULT_CATEGORY_TYPE_ID,
                                              getServiceId(request),
                                              defaultIds,
                                              attributesList);
        }// try
        catch (DataException ex) {
          // Do nothing and let the function return an empty array list
          System.out.println(ex.getMessage());
        }// catch
      }// if
    }
    else {
      long cntTypeId = Long.parseLong((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));

      // Create sql condition for matching "CONTENT_TYPE" to contentTypeName
      SQLCondition sqlConditionContentType = SQLConditionFactory.buildCondition(CATEGORY_TABLE_NAME,
           CONTENT_TYPE, SQLOperator.OP_EQUAL, new DataValue(cntTypeId));
      
      SQLCompoundCondition compoundCond = new SQLCompoundCondition(sqlConditionContentType);
      
      // Do a name match only if the search key is not empty
      if (searchKey != null && searchKey.length() !=0) {
        // Create sql condition for matching "NAME" to the search key
        SQLCondition sqlConditionName = getNameMatchSqlCondition(CATEGORY_TABLE_NAME, 
                                                            columnName,
                                                            searchKey,
                                                            false);
        compoundCond.addCondition(SQLOperator.OP_AND, sqlConditionName);
      }// if

      try {
        DataManager dm = new DataManager();
        CallSettings callsettings = dm.getCallSettings();
        callsettings.setFilteringFlag(false);
        ArrayList attributesList = new ArrayList(3);
        attributesList.add(OID);
        attributesList.add(columnName);
        attributesList.add(CONTENT_TYPE);
        resultList = dm.getPartialContentsByCondition(DataConstants.DEFAULT_CATEGORY_TYPE_ID,
                                                      getServiceId(request),
                                                      compoundCond,
                                                      attributesList,
                                                      false);
      }// try
      catch (DataException ex) {
        // Do nothing and let the function return an empty array list
        System.out.println(ex.getMessage());
      }// catch
    }// else
    return resultList;
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#getColumnName(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public String getColumnName(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    return NAME;
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#getItemsNameList(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.List)
   */
  protected List getItemsNameList(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response,
    List itemsIdList)
    throws Exception {
      
    // Get the content type id
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    int cntTypeId = Integer.parseInt((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));
    String contentTypeName = DataManager.getContentTypeName(cntTypeId);
                                          
    DataManager dm = new DataManager();
    CallSettings callsettings = dm.getCallSettings();
    callsettings.setFilteringFlag(false);

    // Create a list which contains a list of display name
    List returnList = new ArrayList();
    for (int i = 0; i < itemsIdList.size(); i++) {
      
      ContentUID catUid = new ContentUID(getServiceId(request), 
                                          ((Long)itemsIdList.get(i)).intValue(), 
                                          contentTypeName);
      if (dm.categoryExists(catUid) == true) {
        Category cat = dm.getCategory(catUid);
        if (cntTypeId == Qualifier.QUALIFIER_VALUE_CONTENT_TYPE_ID) {
          returnList.add(cat.getStringValue(TableConstants.NAME));
        }
        else {
          returnList.add(cat.getPathName());
        }
      }// if
    }// for

    return returnList;
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#fillUpItemBean(com.broadvision.web.util.ViewDynaBean, java.lang.Object, java.lang.String)
   */
  public void fillUpItemBean(ActionMapping mapping, ActionForm form,
                      HttpServletRequest request, HttpServletResponse response,
                      ViewDynaBean viewBean, Object item, String columnName)
                                                              throws Exception {
                                                                
    super.fillUpItemBean(mapping, form, request, response, viewBean, item, columnName);
    // Get the content type id
    DynaActionForm pickerPopupForm = (DynaActionForm)form;
    int cntTypeId = Integer.parseInt((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));
    String contentTypeName = DataManager.getContentTypeName(cntTypeId);

    ContentUID catUid = new ContentUID(getServiceId(request), 
                                        (int)((Content)item).getOid(), 
                                        contentTypeName);
    DataManager dm = new DataManager();
    CallSettings callsettings = dm.getCallSettings();
    callsettings.setFilteringFlag(false);

    if (dm.categoryExists(catUid) == true) {
      // Create a category
      Category cat = dm.getCategory(catUid);
      // Want to display and save the name with the category path
      if (cntTypeId == Qualifier.QUALIFIER_VALUE_CONTENT_TYPE_ID) {
        PropertyUtils.setSimpleProperty(viewBean, "name", cat.getStringValue(TableConstants.NAME));
        PropertyUtils.setSimpleProperty(viewBean, "nameToSave", cat.getStringValue(TableConstants.NAME));       
      }
      else {
        PropertyUtils.setSimpleProperty(viewBean, "name", cat.getPathName());
        PropertyUtils.setSimpleProperty(viewBean, "nameToSave", cat.getPathName());
      }
    }// if
  }
  
  protected boolean isValidId(int serviceId, int contentTypeId, long id) {
    boolean result = false;
    try {
      DataManager dm = new DataManager();
      CallSettings callsettings = dm.getCallSettings();
      callsettings.setFilteringFlag(false);
      String contentTypeName = DataManager.getContentTypeName(contentTypeId);
      ContentUID uid = new ContentUID(serviceId, id, contentTypeName);
      result = dm.categoryExists(uid);
    }// try
    catch (DataException ex) {
    }// catch
    return result;
  }

  /* (non-Javadoc)
   * @see com.broadvision.manage.common.tools.action.common.BasePickerPopupAction#doItemsListFiltering(java.util.List)
   */
  protected List doItemsListFiltering(ActionMapping mapping, ActionForm form,
                                      HttpServletRequest request, 
                                      HttpServletResponse response,
                                      List listToBeFiltered) {
    try {
      return doListFiltering(mapping, form, request, response, listToBeFiltered, false);
    }// try
    catch (Throwable ex) {
      System.out.println("doItemsListFiltering() failed.Reason:" 
                          + ex.getClass().getName()
                          + " No filtering performed for items list.");
      return listToBeFiltered;
    }// catch
  }

}
